package com.white.webserver.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.white.webserver.common.dto.LoginDto;
import com.white.webserver.common.dto.RegisterDto;
import com.white.webserver.common.lang.Result;
import com.white.webserver.entity.User;
import com.white.webserver.service.IMailService;
import com.white.webserver.service.IUserService;
import com.white.webserver.util.JwtUtils;
import com.white.webserver.util.PasswordUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.time.LocalDateTime;

@RestController
public class AccountController {
    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    IUserService userService;
    @Autowired
    IMailService mailService;

    @Value("${config.check-code.expiration-time}") private int expirationTime;

    // 注册
    @CrossOrigin
    @PostMapping("/register")
    public Result register(@Validated @RequestBody RegisterDto registerDto) {
        User user = userService.getOne(new QueryWrapper<User>().eq("email", registerDto.getEmail()));

        if (PasswordUtils.checkPassword(registerDto.getPassword()) == PasswordUtils.PasswordStrength.LOW)
        {
            return Result.fail("密码强度过低");
        }

        if (user == null)
        {
            return Result.fail("请先获取验证码");
        }

        if (user.getStatus() != 0) {
            return Result.fail("邮箱已被注册");
        }

        if (!user.getCheckCode().equals(registerDto.getCheckCode()))
        {
            return Result.fail("验证码错误");
        }

        LocalDateTime checkTime = user.getCheckTime();
        LocalDateTime nowTime = LocalDateTime.now();
        Duration duration = Duration.between(checkTime, nowTime);
        if (duration.abs().getSeconds() > expirationTime)
        {
            return Result.fail("验证码过期！");
        }

        user.setNickName(registerDto.getNickName());
        user.setPassword(SecureUtil.md5(registerDto.getPassword()));
        user.setCreated(nowTime);
        user.setStatus(1);
        userService.updateById(user);

        return Result.success("注册成功");
    }

    // 登录
    @CrossOrigin
    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response) {
        User user = userService.getOne(new QueryWrapper<User>().eq("email", loginDto.getEmail()));
        Assert.notNull(user, "用户不存在");

        if(!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))) {
            return Result.fail("密码错误");
        }
        String jwt = jwtUtils.generateToken(user.getId());
        response.setHeader("Authorization", jwt);
        response.setHeader("Access-Control-Expose-Headers", "Authorization");

        LocalDateTime nowTime = LocalDateTime.now();
        user.setLastLogin(nowTime);
        userService.updateById(user);

        return Result.success(MapUtil.builder()
                .put("id", user.getId())
                .put("nickname", user.getNickName())
                .put("avatar", user.getAvatar())
                .put("email", user.getEmail())
                .put("created", user.getCreated())
                .map()
        );
    }

    // 登出
    @GetMapping("/logout")
    @RequiresAuthentication
    public Result logout() {
        SecurityUtils.getSubject().logout();
        return Result.success("已登出");
    }
}